package com.aosan.website.auth.service

import com.alibaba.fastjson.JSONObject
import com.aosan.website.admin.entity.SysLoginLogEntity
import com.aosan.website.admin.feign.LoginLogClient
import com.aosan.website.common.core.utils.ResultData
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.cloud.context.config.annotation.RefreshScope
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Service
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.RestTemplate

@RefreshScope
@Service
class AuthService(
        val restTemplate: RestTemplate,
        val loginLogClient: LoginLogClient
) {

    private val logger = LoggerFactory.getLogger(this::class.java)

    @Value("\${spring.application.name}")
    val serverName: String = ""

    @Value("\${auth.client}")
    val clientId: String = ""

    @Value("\${auth.secret}")
    val clientSecret: String = ""


    /**
     * 获取登录Token
     * @param username 用户名
     * @param password 密码
     */
    fun fetchLoginToken(username: String, password: String): Any? {
        val tokenUrl = "http://${serverName}/oauth/token"
        val loginMap = LinkedMultiValueMap<String, String>()
        loginMap.apply {
            add("username", username)
            add("password", password)
            add("grant_type", "password")
            add("client_id", clientId)
            add("client_secret", clientSecret)
        }
        val headers = HttpHeaders()
        headers.add("Content-Type", "application/x-www-form-urlencoded")
        val request = HttpEntity(loginMap, headers)
        return try {
            val token = restTemplate.postForObject(tokenUrl, request, JSONObject::class.java)
            val loginLogEntity = SysLoginLogEntity().apply {
            }
//            loginLogClient.saveLoginLog(loginLogEntity)
            ResultData.ok(token?.apply {
                remove("scope")
                remove("token_type")
                remove("expires_in")
                remove("jti")
            })
        } catch (e: Exception) {
            logger.error(e.message)
            e.message?.let { ResultData.err("用户名密码错误", it) }
        }
    }
}